<template>
  <div>
       <div class="head">
      <div class="img">
        <img src="../../assets/NJUST.jpeg" />
      </div>
      <div class="person">
        <img src="../../assets/用户名.png" />
       <li class="li1"><router-link to="/person"><span>个人主页</span></router-link></li>
      </div>
    </div>

    <div class="crumbs">
        <nav>
            <a href="/Home1">首页</a><span></span>
            <!-- <a href="#">XXXX标准</a><span>/</span>
            <a href="#">XXXX项目</a> -->
        </nav>
    </div>
  <div class="equipment-list">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="设备计划购入清单" name="first">
        <div class="filter-bar">
          <div class="filter-item">
            <el-input
              v-model="equipmentSearchKey"
              placeholder="搜索标准名称/项目名称/设备名称"
              prefix-icon="el-icon-search"
              clearable
              @input="handleEquipmentSearch">
            </el-input>
          </div>
          <div class="filter-item">
            <el-select 
              v-model="equipmentStatusFilter" 
              placeholder="状态筛选"
              clearable
              @change="handleStatusChange">
              <el-option
                v-for="item in equipmentStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>

        <div class="table-container">
          <el-table 
            :data="filteredData" 
            style="width: 100%"
            v-loading="loading"
            border>
            <el-table-column 
              type="index" 
              label="序号" 
              width="80"
              :index="indexMethod">
            </el-table-column>
            <el-table-column 
              prop="details[0].staName" 
              label="标准名称"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="details[0].pjName" 
              label="项目名称"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="details[0].pjGB" 
              label="标准编号（含年号）及条款号"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="details[0].ename" 
              label="设备名称"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="details[0].soName" 
              label="解决方案"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="oStatus" 
              label="状态"
              width="100">
              <template slot-scope="scope">
                <el-tag 
                  :type="getStatusType(scope.row.oStatus)"
                  size="small">
                  {{ scope.row.oStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column 
              label="操作"
              width="100"
              fixed="right">
              <template slot-scope="scope">
                <el-button 
                  @click="handleDeleteOrder(scope.row.oId, scope.row)" 
                  type="text" 
                  size="small">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="样品清单" name="second">
        <div class="filter-bar">
          <div class="filter-item">
            <el-input
              v-model="sampleSearchKey"
              placeholder="搜索标准名称/样品名称/生产厂家"
              prefix-icon="el-icon-search"
              clearable
              @input="handleSampleSearch">
            </el-input>
          </div>
          <div class="filter-item">
            <el-select 
              v-model="sampleStatusFilter" 
              placeholder="状态筛选"
              clearable
              @change="handleStatusChange">
              <el-option
                v-for="item in sampleStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>

        <div class="table-container">
          <el-table 
            :data="filteredData" 
            style="width: 100%"
            v-loading="loading"
            border>
            <el-table-column 
              type="index" 
              label="序号" 
              width="80"
              :index="indexMethod">
            </el-table-column>
            <el-table-column 
              prop="staName" 
              label="标准名称"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="staGB" 
              label="标准编号（含年号）"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="spName" 
              label="样品名称"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="spFactory" 
              label="生产厂家"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="spoGg" 
              label="规格型号"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="spoNeed" 
              label="申请需求（文本）"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column 
              prop="spoStatus" 
              label="状态"
              width="100">
              <template slot-scope="scope">
                <el-tag 
                  :type="getStatusType(scope.row.spoStatus)"
                  size="small">
                  {{ scope.row.spoStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column 
              label="操作"
              width="150"
              fixed="right"
              align="center">
              <template slot-scope="scope">
                <el-button 
                  @click="handleDeleteSpo(scope.row.spoId, scope.row)" 
                  type="text" 
                  size="small">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button 
                  @click="showDialog(scope.row)" 
                  type="text" 
                  size="small">
                  <i class="el-icon-edit"></i> 编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 15, 20, 30]"
        :page-size="pageSize"
        :total="totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        background>
      </el-pagination>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog 
      :visible.sync="dialogVisible" 
      title="规格型号申请"
      width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="规格型号">
          <el-select 
            v-model="form.modelNumber" 
            placeholder="请选择"
            style="width: 100%">
            <el-option
              v-for="number in modelNumbers"
              :key="number"
              :label="number.toString()"
              :value="number">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请需求">
          <el-input 
            v-model="form.demand" 
            type="textarea"
            :rows="4"
            placeholder="请输入申请需求">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false, // 控制加入清单弹窗显示
      form: {
        modelNumber: '', // 规���型号
        demand: ''    // 申请需求
      },
      activeTab: 'first',
      equipmentData: [

      ],
      sampleData: [

      ],
      modelNumbers: [],
      currentData: [],//初始化为第一个列表的传入数据
      pageSize: 10,//一页显示的数据数
      currentPage: 1,//当前页，初始化为第一页，点击则更新
      totalItems: 0,
      loading: false, // 加loading状态
      equipmentStatusFilter: '', // 设备清单状态筛选
      sampleStatusFilter: '', // 样品清单状态筛选
      equipmentStatusOptions: [
        { label: '全部', value: '' },
        { label: '计划采购', value: '计划采购' },
        { label: '采购完成', value: '采购完成' }
      ],
      sampleStatusOptions: [
        { label: '全部', value: '' },
        { label: '已发放', value: '已发放' },
        { label: '未发放', value: '未发放' }
      ],
      originalEquipmentData: [], // 分别存储两个列表的原始数据
      originalSampleData: [],
      error: null,
      equipmentSearchKey: '', // 设备清单搜索关键字
      sampleSearchKey: '', // 样品清单搜索关键字
      searchTimeout: null, // 搜索防抖定时器
      selectedSpoId:''
    };
  },
  created:function() {
    this.findOrder();
    this.findSpo();
    

  },
  computed: {
    filteredData() {
      try {
        let data = [];
        if (this.activeTab === 'first') {
          // 设备清单数据过滤
          data = this.equipmentData.filter(item => {
            if (this.equipmentSearchKey) {
              const keyword = this.equipmentSearchKey.toLowerCase();
              return (
                (item.details[0].staName && item.details[0].staName.toLowerCase().includes(keyword)) ||
                (item.details[0].pjName && item.details[0].pjName.toLowerCase().includes(keyword)) ||
                (item.details[0].ename && item.details[0].ename.toLowerCase().includes(keyword))
              );
            }
            if (this.equipmentStatusFilter) {
              return item.oStatus === this.equipmentStatusFilter;
            }
            return true;
          });
        } else {
          // 样品清单数据过滤
          data = this.sampleData.filter(item => {
            if (this.sampleSearchKey) {
              const keyword = this.sampleSearchKey.toLowerCase();
              return (
                (item.staName && item.staName.toLowerCase().includes(keyword)) ||
                (item.spName && item.spName.toLowerCase().includes(keyword)) ||
                (item.spFactory && item.spFactory.toLowerCase().includes(keyword))
              );
            }
            if (this.sampleStatusFilter) {
              return item.spoStatus === this.sampleStatusFilter;
            }
            return true;
          });
        }
        
        // 分页处理
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        return data.slice(start, end);
      } catch (error) {
        console.error('数据过滤错误:', error);
        return [];
      }
    },

    totalItems() {
      return this.activeTab === 'first' ? 
        this.equipmentData.length : 
        this.sampleData.length;
    },

    // 添加禁用状态计算
    isSubmitDisabled() {
      return !this.form.modelNumber || this.loading;
    }
  },
  methods: {
    // 获取设备清单数据
    async findOrder() {
      this.loading = true;
      try {
        const response = await this.$http.get("/findOrdersByUID");
        if (response.data) {
          this.equipmentData = response.data;
          this.originalEquipmentData = [...this.equipmentData];
          if (this.activeTab === 'first') {
            this.currentData = this.equipmentData;
            this.totalItems = this.equipmentData.length;
          }
          console.log('设备清单数据:', this.equipmentData); // 添加调试日志
        }
      } catch (error) {
        console.error('获取设备清单失败:', error);
        this.$message.error('获取设备清单失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 获取样品清单数据
    async findSpo() {
      this.loading = true;
      try {
        const response = await this.$http.get("/findSpoByUID");
        if (response.data) {
          this.sampleData = response.data;
          this.originalSampleData = [...this.sampleData];
          if (this.activeTab === 'second') {
            this.currentData = this.sampleData;
            this.totalItems = this.sampleData.length;
          }
          console.log('样品清单数据:', this.sampleData); // 添加调试日志
        }
      } catch (error) {
        console.error('获取样品清单失败:', error);
        this.$message.error('获取样品清单失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 添加设备清单搜索方法
    handleEquipmentSearch() {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }
      this.searchTimeout = setTimeout(() => {
        this.currentPage = 1;
        const keyword = this.equipmentSearchKey.toLowerCase();
        if (!keyword) {
          this.currentData = this.filterByStatus(this.originalEquipmentData);
        } else {
          const filtered = this.originalEquipmentData.filter(item => 
            (item.details[0].staName && item.details[0].staName.toLowerCase().includes(keyword)) ||
            (item.details[0].pjName && item.details[0].pjName.toLowerCase().includes(keyword)) ||
            (item.details[0].ename && item.details[0].ename.toLowerCase().includes(keyword))
          );
          this.currentData = this.filterByStatus(filtered);
        }
        this.totalItems = this.currentData.length;
      }, 300);
    },

    // 添加样品清单搜索方法
    handleSampleSearch() {
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }
      this.searchTimeout = setTimeout(() => {
        this.currentPage = 1;
        const keyword = this.sampleSearchKey.toLowerCase();
        if (!keyword) {
          this.currentData = this.filterByStatus(this.originalSampleData);
        } else {
          const filtered = this.originalSampleData.filter(item => 
            (item.staName && item.staName.toLowerCase().includes(keyword)) ||
            (item.spName && item.spName.toLowerCase().includes(keyword)) ||
            (item.spFactory && item.spFactory.toLowerCase().includes(keyword))
          );
          this.currentData = this.filterByStatus(filtered);
        }
        this.totalItems = this.currentData.length;
      }, 300);
    },

    // 添加状态筛选辅助方法
    filterByStatus(data) {
      const status = this.activeTab === 'first' ? 
        this.equipmentStatusFilter : 
        this.sampleStatusFilter;
      
      if (!status) return data;
      
      return data.filter(item => {
        const itemStatus = this.activeTab === 'first' ? 
          item.oStatus : 
          item.spoStatus;
        return itemStatus === status;
      });
    },

    // 修改标签页切换处理方法
    handleTabClick(tab) {
      try {
        this.activeTab = tab.name;
        this.error = null;
        
        // 重置搜索和筛选条件
        if (tab.name === 'first') {
          this.equipmentStatusFilter = '';
          this.equipmentSearchKey = '';
          this.currentData = this.equipmentData;
        } else {
          this.sampleStatusFilter = '';
          this.sampleSearchKey = '';
          this.currentData = this.sampleData;
        }
        
        // 重置分页
        this.currentPage = 1;
        this.totalItems = this.currentData.length;
        
        console.log('切换标签页:', {
          activeTab: this.activeTab,
          currentData: this.currentData,
          totalItems: this.totalItems
        });
      } catch (error) {
        console.error('标签页切换错误:', error);
        this.$message.error('切换失败，请重试');
      }
    },

    // 修改状态筛选处理方法
    handleStatusChange(value) {
      try {
        this.currentPage = 1;
        const sourceData = this.activeTab === 'first' ? 
          this.originalEquipmentData : 
          this.originalSampleData;

        // 先按搜索关键字筛选
        let filtered = sourceData;
        const searchKey = this.activeTab === 'first' ? 
          this.equipmentSearchKey : 
          this.sampleSearchKey;

        if (searchKey) {
          if (this.activeTab === 'first') {
            this.handleEquipmentSearch();
            return;
          } else {
            this.handleSampleSearch();
            return;
          }
        }

        // 再按状态筛选
        if (!value) {
          this.currentData = filtered;
        } else {
          this.currentData = this.filterByStatus(filtered);
        }
        
        this.totalItems = this.currentData.length;
      } catch (error) {
        console.error('筛选处理错误:', error);
        this.$message.error('筛选处理失败，请重试');
      }
    },

    // 优化编辑对话框显示
    async showDialog(row) {
      try {
        this.selectedSpoId = row.spoId;
        const spId = row.spId;
        if (!spId) {
          throw new Error('无效的样品ID');
        }
        
        this.loading = true;
        const response = await this.$http.get(`/findSample/${spId}`);
        
        if (response.data && response.data.spGg) {
          this.selectedRow = row;
          this.modelNumbers = response.data.spGg.split('/').filter(Boolean);
          this.dialogVisible = true;
        } else {
          throw new Error('获取规格型号数据失败');
        }
      } catch (error) {
        console.error('显示编辑对话框错误:', error);
        this.$message.error('打开编辑窗口失败，请重试');
      } finally {
        this.loading = false;
      }
    },

    // 优化表单提交
    async handleSubmit() {
      try {
        if (!this.form.modelNumber) {
          this.$message.warning('请选择规格型号');
          return;
        }
        
        const submitData = {
          spId: this.selectedSpoId,
          spoGg: this.form.modelNumber,
          spoNeed: this.form.demand
        }

        // 这里添加表单提交的逻辑
        // ...
        this.$http.put("/updateSpo", submitData).then(() => {
          this.$message({
            type: 'success',
            message: '更新成功!'
          });
          this.findSpo();
        }).catch(error => {
          this.$message.error('更新失败，请重试');
          console.error('更新失败:', error);
        });


        this.dialogVisible = false;
        this.resetForm();
      } catch (error) {
        console.error('提交表单错误:', error);
        this.$message.error('提交失败，请重试');
      }
    },

    // 重置表单
    resetForm() {
      this.form = {
        modelNumber: '',
        demand: ''
      };
    },

    // 优化分页计算
    indexMethod(index) {
      try {
        return (this.currentPage - 1) * this.pageSize + index + 1;
      } catch (error) {
        console.error('序号计算错误:', error);
        return index + 1;
      }
    },

    // 修改状态类型判断方法
    getStatusType(status) {
      const statusMap = {
        '计划采购': 'warning',
        '采购完成': 'success',
        '已发放': 'success',
        '未发放': 'warning'
      };
      return statusMap[status] || 'info';
    },

    // 修改分页处理方法
    handleCurrentChange(val) {
      this.currentPage = val;
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },

    // 修改设备清单删除方法
    handleDeleteOrder(oId, row) {
      this.$confirm('确认删除该设备记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        this.$http.put(`/deleteOrders/${oId}`).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 重新获取数据
          this.findOrder();
        }).catch(error => {
          this.$message.error('删除失败，请重试');
          console.error('删除失败:', error);
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDeleteSpo(spoId, row) {
      this.$confirm('确认删除该样品记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        this.$http.put(`/deleteSpo/${spoId}`).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 重新获取数据
          this.findSpo();
        }).catch(error => {
          this.$message.error('删除失败，请重试');
          console.error('删除失败:', error);
        }).finally(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 删除后更新列表数据
    updateList() {
      if (this.activeTab === 'first') {
        this.findOrder();
      } else {
        this.findSpo();
      }
    },
  },

  // 添加监听器
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.resetForm();
      }
    }
  }
};
</script>

<style scoped>
  .head {
    width: 100vw;
    background-color: #abe0f3;
    height: 6vh;
  }

    .head .img {
      height: 100%;
      float: left;
    }

      .head .img img {
        height: 100%;
      }

    .head .person {
      float: right;
      height: 42%;
    }

      .head .person img {
        margin-top: 15px;
        margin-right: 7px;
        height: 100%;
        float: left;
      }

      .head .person li {
        margin-top: 20px;
        margin-right: 70px;
        display: block;
        float: left;
        font-size: 18px;
      }

.crumbs {
  display: flex; /* 使用Flexbox布局 */
  align-items: center; /* 垂直居中 */
  background-color: #f0f0f0; /* 背景颜色 */
  padding: 10px 20px; /* 内边距 */
}

.crumbs nav a {
  margin-left: 15px;
  text-decoration: none;
  color: #333;
}

.equipment-list {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.table-container {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.pagination-container {
  padding: 20px;
  text-align: center;
  background: white;
  border-top: 1px solid #EBEEF5;
}

/* Element UI 组件样式优化 */
:deep(.el-table) {
  margin-bottom: 0;
}

:deep(.el-table th) {
  background-color: #F5F7FA;
  color: #606266;
  font-weight: 500;
}

:deep(.el-table--border th, .el-table--border td) {
  border-right: 1px solid #EBEEF5;
}

:deep(.el-button--text) {
  color: #4CAF50;
  padding: 0;
}

:deep(.el-button--text:hover) {
  color: #45a049;
}

:deep(.el-button--text i) {
  margin-right: 4px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

:deep(.el-pagination) {
  font-weight: normal;
  color: #606266;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #4CAF50;
  color: white;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #4CAF50;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

:deep(.el-dialog__footer) {
  padding: 15px 30px 20px;
  text-align: right;
  border-top: 1px solid #EBEEF5;
}

/* 添加删除按钮的悬停效果 */
:deep(.el-button--text.delete-button) {
  color: #f56c6c;
}

:deep(.el-button--text.delete-button:hover) {
  color: #f78989;
}

/* 添加确认对话框样式 */
:deep(.el-message-box) {
  padding: 20px;
  border-radius: 4px;
}

:deep(.el-message-box__title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-message-box__content) {
  padding: 20px 0;
}

:deep(.el-message-box__btns) {
  padding-top: 15px;
  border-top: 1px solid #EBEEF5;
}

/* 添加筛选区域样式 */
.filter-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.filter-item {
  flex: 1;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-input__inner:hover),
:deep(.el-input__inner:focus) {
  border-color: #4CAF50;
}

:deep(.el-input__prefix) {
  color: #909399;
}

:deep(.el-input.is-active .el-input__inner) {
  border-color: #4CAF50;
}
</style>
